import java.io.IOException;
import java.io.ObjectOutputStream;

public class Sender implements Runnable {
    private ObjectOutputStream m_out;
    private Thread m_thread;
    MessageQueue m_messageQueue;

    public Sender(ObjectOutputStream out, MessageQueue messageQueue)
    {
        m_out = out;
        m_messageQueue = messageQueue;
        m_thread = new Thread(this);
    }

    public void setDaemon(boolean isDaemon)
    {
        m_thread.setDaemon(isDaemon);
    }

    public void start()
    {
        m_thread.start();
    }

    public void run()
    {
        while (true)
        {
            System.out.println("send queue " + m_messageQueue.queue.size());
            if (!m_messageQueue.isEmpty())
            {
                Message message = m_messageQueue.get();
                m_messageQueue.pop();
                try
                {
                    m_out.writeInt(message.length);
                    m_out.writeInt(message.type);
                    m_out.write(message.data, 0, message.length);
                    m_out.flush();
                    System.out.println("send " + message.length + " " + message.type + "\n");
                }
                catch(IOException ioException){
                    ioException.printStackTrace();
                }
                finally {
                    //System.out.println("send " + message.length + " " + message.type + "\n");
                }

            }
            else
            {
                try
                {
                    m_thread.sleep(1);
                    System.out.println("I love sleep....zzzzzzz");
                }
                catch (InterruptedException e)
                {
                    break;
                }
            }
        }
    }

    public void stop()
    {
        m_thread.interrupt();
    }
}
